const express = require('express');
const path = require('node:path');
const pool = require(path.resolve(__dirname, '../sqlPool.js'));
const multer = require('multer');
const jwt = require('jsonwebtoken');
const router = express.Router();
const fs = require('fs');

//已通过审核的博客的分页查询
router.post('/getAllPageBlog', (req, res) => {
	if (req.body.limit) {
		let sql = `SELECT * FROM blogmsg WHERE state="fulfilled" LIMIT ${req.body.limit} OFFSET ${req.body.offset}`;
		pool.query(sql, (error, result) => {
			if (error) {
				console.log(error);
				return res.send({
					state: 'error',
				});
			} else {
				return res.send({
					state: 'ok',
					data: result,
				});
			}
		});
	}
});

//获取所有已通过审核的博客列表长度
router.post('/getAllBlogTotal', (req, res) => {
	let sql = `SELECT * FROM blogmsg WHERE state="fulfilled"`;
	pool.query(sql, (error, result) => {
		if (error) {
			console.log(error);
			return res.send({
				state: 'error',
			});
		} else {
			return res.send({
				state: 'ok',
				data: result.length,
			});
		}
	});
});

//更新博客状态
router.post('/updateBlogState', (req, res) => {
	if (req.body.state && req.body.id) {
		let sql = `UPDATE blogmsg SET state="${req.body.state}" WHERE id=${req.body.id}`;
		pool.query(sql, (error, result) => {
			if (error || result.changedRows === 0) {
				console.log(error);
				return res.send({
					state: 'error',
				});
			} else {
				return res.send({
					state: 'ok',
				});
			}
		});
	}
});

//审核未通过的列表的分页查询
router.post('/getAllPendingBlog', (req, res) => {
	if (req.body.limit) {
		let sql = `SELECT * FROM blogmsg WHERE state="pending" LIMIT ${req.body.limit} OFFSET ${req.body.offset}`;
		pool.query(sql, (error, result) => {
			if (error) {
				console.log(error);
				return res.send({
					state: 'error',
				});
			} else {
				return res.send({
					state: 'ok',
					data: result,
				});
			}
		});
	}
});

//获取所有未审核通过的博客列表长度
router.post('/getAllPendingBlogTotal', (req, res) => {
	let sql = `SELECT * FROM blogmsg WHERE state="pending"`;
	pool.query(sql, (error, result) => {
		if (error) {
			console.log(error);
			return res.send({
				state: 'error',
			});
		} else {
			return res.send({
				state: 'ok',
				data: result.length,
			});
		}
	});
});

router.post('/getPageTotal', (req, res) => {
	if (req.body.searchVal) {
		let sql = `SELECT * FROM blogmsg WHERE title LIKE '%${req.body.searchVal}%' AND state="fulfilled"`;
		let data1 = '';
		pool.query(sql, (error, result) => {
			if (error) {
				console.log(error);
				return res.send({
					state: 'error',
				});
			} else {
				data1 = result;
				sql = `SELECT * FROM blogmsg WHERE uploader LIKE '%${req.body.searchVal}%' AND state="fulfilled"`;
				pool.query(sql, (error, result) => {
					if (error) {
						console.log(error);
						return res.send({
							state: 'error',
						});
					}
					let data = [...data1, ...result];
					if (data.length === 0) {
						return res.send({
							state: 'none',
						});
					} else {
						return res.send({
							state: 'ok',
							pageLength: data.length,
						});
					}
				});
			}
		});
	} else {
		return res.send({
			state: 'error',
		});
	}
});

router.post('/searchBlog', (req, res) => {
	if (req.body.searchVal && req.body.limit) {
		let sql = `SELECT * FROM blogmsg WHERE title LIKE '%${
			req.body.searchVal
		}%' AND state="fulfilled" LIMIT ${req.body.limit / 2} OFFSET ${
			req.body.offset / 2
		}`;
		pool.query(sql, (error, result) => {
			let data1 = [];
			if (error) {
				return res.send({
					state: 'error',
				});
			} else if (result.length === 0) {
				sql = `SELECT * FROM blogmsg WHERE uploader LIKE '%${
					req.body.searchVal
				}%' AND state="fulfilled" LIMIT ${req.body.limit / 2} OFFSET ${
					req.body.offset / 2
				}`;
			} else {
				sql = `SELECT * FROM blogmsg WHERE uploader LIKE '%${
					req.body.searchVal
				}%' AND state="fulfilled" LIMIT ${req.body.limit / 2} OFFSET ${
					req.body.offset / 2
				}`;
				data1 = result;
			}
			pool.query(sql, (error, result) => {
				if (error) {
					return res.send({
						state: 'error',
					});
				}
				let data = [...data1, ...result];
				if (data.length === 0) {
					return res.send({
						state: 'none',
					});
				} else {
					return res.send({
						state: 'ok',
						data,
					});
				}
			});
		});
	} else {
		return res.send({
			state: 'error',
		});
	}
});

router.post('/getAppointBlog', (req, res) => {
	if (req.body.id) {
		let sql = `SELECT * FROM blogmsg WHERE id= ${req.body.id} AND state="fulfilled"`;
		pool.query(sql, (error, result) => {
			if (error) {
				console.log(error);
				return res.send({
					state: 'error',
				});
			} else {
				return res.send({
					state: 'ok',
					data: result,
				});
			}
		});
	} else {
		return res.send({
			state: 'error',
		});
	}
});

router.post('/getPartCategoryBlog', (req, res) => {
	if (req.body.categoryname && req.body.limit) {
		let sql = `SELECT * FROM blogmsg WHERE category='${req.body.categoryname}' AND state="fulfilled" ORDER BY id DESC LIMIT ${req.body.limit} `;
		pool.query(sql, (error, result) => {
			if (error) {
				console.log(error);
				return res.send({
					state: 'error',
				});
			} else {
				return res.send({
					state: 'ok',
					data: result,
				});
			}
		});
	}
});

router.post('/uploadBlog', (req, res) => {
	if (
		req.body.title &&
		req.body.username &&
		req.body.content &&
		req.body.category &&
		req.body.uploadDate
	) {
		let sql = '';
		let uploadDate = JSON.stringify(req.body.uploadDate);
		if (req.body.cover) {
			sql = `INSERT INTO blogmsg(uploader,category,title,content,cover,uploaddate,state) VALUES('${
				req.body.username
			}','${req.body.category}','${req.body.title}',${JSON.stringify(
				req.body.content
			)},'${req.body.cover}','${uploadDate}',"pending")`;
			pool.query(sql, (error, result) => {
				if (error) {
					console.log(error);
					return res.send({
						state: 'error',
					});
				} else {
					return res.send({
						state: 'ok',
					});
				}
			});
		} else {
			sql = `INSERT INTO blogmsg(uploader,category,title,content,uploaddate,state) VALUES('${req.body.username}','${req.body.category}','${req.body.title}','${req.body.content}','${uploadDate}',"pending")`;
			pool.query(sql, (error, result) => {
				if (error) {
					console.log(error);
					return res.send({
						state: 'error',
					});
				} else {
					return res.send({
						state: 'ok',
					});
				}
			});
		}
	} else {
		return res.send({
			state: 'error',
		});
	}
});

router.get('/getCategory', (req, res) => {
	let sql = `SELECT categoryname from category`;
	pool.query(sql, (error, result) => {
		if (error) {
			console.log(error);
			return res.send({
				state: 'error',
			});
		} else {
			return res.send({
				state: 'ok',
				data: result,
			});
		}
	});
});

// 设置存储配置
const storage = multer.diskStorage({
	destination: function (req, file, cb) {
		cb(null, 'uploads/'); // 确保这个文件夹已经存在
	},
	filename: function (req, file, cb) {
		cb(
			null,
			req.body.username + '-' + file.fieldname + '-' + req.body.dateNow
		);
	},
});
const upload = multer({ storage: storage });

//用户博客上传图片，接收multipart/form-data
router.post('/uploadBlogImage', upload.single('blogImageFile'), (req, res) => {
	fs.readFile(
		path.resolve(
			__dirname,
			'../uploads/' +
				req.body.username +
				'-' +
				req.file.fieldname +
				'-' +
				req.body.dateNow
		),
		(err, data) => {
			if (err) {
				return res.send({
					errno: 1,
					message: err,
				});
			} else {
				const base64String = data.toString('base64');
				const dataURL =
					'data:application/octet-stream;base64,' + base64String;
				return res.send({
					errno: 0,
					data: {
						url: dataURL,
					},
				});
			}
		}
	);
});

//查询所有博客，得到最近发布的limit篇
router.post('/getUserPartBlog', (req, res) => {
	if (req.body.limit) {
		let sql = `SELECT * FROM blogmsg WHERE state="fulfilled" ORDER BY id DESC LIMIT ${req.body.limit} `;
		pool.query(sql, (error, result) => {
			if (error) {
				console.log(error);
				return res.send({
					state: 'error',
				});
			} else {
				return res.send({
					state: 'ok',
					data: result,
				});
			}
		});
	}
});

//博客的分页查询
router.post('/getUserPageBlog', (req, res) => {
	if (req.body.limit && req.body.uploader) {
		let sql = `SELECT * FROM blogmsg WHERE uploader='${req.body.uploader}' AND state="fulfilled" LIMIT ${req.body.limit} OFFSET ${req.body.offset}`;
		pool.query(sql, (error, result) => {
			if (error) {
				console.log(error);
				return res.send({
					state: 'error',
				});
			} else {
				return res.send({
					state: 'ok',
					data: result,
				});
			}
		});
	}
});

//查询所有博客
router.post('/getUserBlog', (req, res) => {
	if (req.body.uploader) {
		let sql = `SELECT * FROM blogmsg WHERE uploader='${req.body.uploader}' AND state="fulfilled"`;
		pool.query(sql, (error, result) => {
			if (error) {
				console.log(error);
				return res.send({
					state: 'error',
				});
			}
			if (result[0]) {
				return res.send({
					state: 'ok',
					data: result,
				});
			} else {
				return res.send({
					state: 'none',
				});
			}
		});
	} else {
		return res.send({
			state: 'error',
		});
	}
});

module.exports = router;
